package guda.house.biz.bo.impl;

import guda.house.biz.bo.WaterFeeBO;
import guda.house.biz.query.ElecRuleQuery;
import guda.house.biz.query.WaterRuleQuery;
import guda.house.dal.dao.*;
import guda.house.dal.dataobject.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

/**
 * Created by well on 15/11/15.
 */
public class WaterFeeBOImpl implements WaterFeeBO {

    private final static Logger logger = LoggerFactory.getLogger(ElecFeeBOImpl.class);
    @Autowired
    private WaterRuleDAO waterRuleDAO;
    @Autowired
    private UnitDAO unitDAO;
    @Autowired
    private BuildingDAO buildingDAO;
    @Autowired
    private SuiteDAO suiteDAO;

    @Override
    public long countWaterFee(Long villageId,Long suiteId, int elecRecord) {
        SuiteDO suiteById = suiteDAO.getSuiteById(suiteId);
       // UnitDO unitById = unitDAO.getUnitById(suiteById.getUnitId());
        //BuildingDO buildingById = buildingDAO.getBuildingById(unitById.getBuildingId());
        WaterRuleQuery waterRuleQuery = new WaterRuleQuery();
        waterRuleQuery.setVillageId(villageId);
        waterRuleQuery.setBuildingTypeId(suiteById.getBuildingTypeId());
        List<WaterRuleDO> waterRuleDOs = waterRuleDAO.selectForView(waterRuleQuery);
        if(waterRuleDOs.size() == 0 ){
            logger.warn("小区ID" + villageId + "没有设置电费规则。。");
            return 0L;
        }
        //从大到小排序
        Collections.sort(waterRuleDOs, new Comparator<WaterRuleDO>() {
            @Override
            public int compare(WaterRuleDO o1, WaterRuleDO o2) {
                return o2.getMinValue() - o1.getMinValue();
            }
        });
        long total = 0l;
        Iterator<WaterRuleDO> iterator = waterRuleDOs.iterator();
        while(iterator.hasNext()){
            WaterRuleDO next = iterator.next();
            if(next.getMaxValue() == null){
                total  = total + (elecRecord - next.getMinValue())*next.getFeeUnit();
                iterator.remove();
                break;
            }
            if(elecRecord< next.getMinValue()){
                iterator.remove();
                continue;
            }
            if(elecRecord >  next.getMinValue() && elecRecord < next.getMaxValue()){
                total  = total + (elecRecord - next.getMinValue())*next.getFeeUnit();
                iterator.remove();
                break;
            }

            if(elecRecord > next.getMaxValue()){
                total  = total + (elecRecord - next.getMaxValue())*next.getFeeUnit();
                iterator.remove();
                break;
            }
        }
        for(WaterRuleDO water:waterRuleDOs){
            total = total + (water.getMaxValue()  - water.getMinValue())*water.getFeeUnit();
        }

        return total;
    }
}
